import time
import hmac
import hashlib
import base64
import urllib.parse
import click
import requests
from pathlib import Path


def ddsecret():
    timestamp = str(round(time.time() * 1000))
    t = time.localtime()
    date = f'{t.tm_hour:02}:{t.tm_min:02}'
    secret = 'SEC9cecc2366ca1e3728625861c39ab71be4dfe1afccd71cdca2f8fd1ddd95f6943'
    secret_enc = secret.encode('utf-8')
    string_to_sign = f'{timestamp}\n{secret}'
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc,
                         digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    return timestamp, sign, date


def dealSampleSheet(samplesheet):
    with open(samplesheet) as ssf:
        _samples = []
        flag = 0
        for i in ssf:
            if flag == 0:
                if i.startswith('Sample_ID'):
                    flag = 1
                    continue
                continue
            if flag == 1:
                _samples.append(i.split(',')[0])
        return _samples


@click.command()
@click.option('-ss', '--samplesheet', required=True, type=str, help="samplesheet file of bcl2fastq")
@click.option('-id', '--inputdir', required=True, type=str, help="directory of pipeline")
def main(samplesheet, inputdir):
    samples = dealSampleSheet(samplesheet)
    outdir = Path(inputdir)
    outdir = outdir.absolute()

    reportFasta = {}
    # reportBlast = {}
    while 1:
        for i, e in enumerate(samples):
            fasta = outdir / Path(f'{e}/{e}.remained.fasta')
            # blast = outdir / Path(f'{e}/{e}.nt_v5.parse.xls')

            timestamp, sign, date = ddsecret()
            headers = {'Content-Type': 'application/json'}
            url = f'https://oapi.dingtalk.com/robot/send?access_token=c88766070cf41652b80038f773f20a92bbc1b1439d1abc4602f946fa68ad89a3&timestamp={timestamp}&sign={sign}'
            if fasta not in reportFasta and fasta.exists():
                reportFasta[fasta] = 0
                json={
                    "msgtype": "text",
                    "text": { "content": f"{i+1} {date} {e} 可以投递blastNT了" }
                    }
                resp=requests.post(url=url,headers=headers,json=json)
            # if blast not in reportBlast and blast.exists():
            #     reportBlast[blast] = 0
            #     json={
            #         "msgtype": "text",
            #         "text": { "content": f"{date} {e} blastNT结果已出" }
            #         }
            #     resp=requests.post(url=url,headers=headers,json=json)
            #     time.sleep(3)
        if len(reportFasta) == len(samples):
            break
        time.sleep(30)

if __name__ == "__main__":
    main()
